package com.zwcl.common.core.utils;

import com.zwcl.common.core.constant.Constants;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 生成 MD5 的工具类
 */
public class MD5Utils {

    public static String encode(String plaintext) {
        try {
            return DigestUtils.md5Hex(plaintext.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException var2) {
            throw new RuntimeException(var2);
        }
    }

    public static String getMd5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 加密解密算法 执行一次加密，两次解密
     */
    public static String convertMD5(String inStr) {

        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;
    }

    public static byte[] computeMD5Hash(InputStream is) throws IOException {
        return DigestUtils.md5(is);
    }

    public static byte[] computeMD5Hash(byte[] input) {
        return DigestUtils.md5(input);
    }

    public static String md5Hex(File file) throws FileNotFoundException, IOException {
        return Hex.encodeHexString(computeMD5Hash(file));
    }

    public static String md5Hex(String utf8Content) {
        return Hex.encodeHexString(computeMD5Hash(utf8Content.getBytes(StandardCharsets.UTF_8)));
    }

    public static String md5Hex(byte[] input) {
        return Hex.encodeHexString(computeMD5Hash(input));
    }

    public static byte[] computeMD5Hash(File file) throws FileNotFoundException, IOException {
        FileInputStream input = null;
        byte[] var2;
        try {
            input = new FileInputStream(file);
            var2 = computeMD5Hash((InputStream)input);
        } finally {
            if (input != null) {
                input.close();
            }
        }

        return var2;
    }
}
